package com.example.restatr.Atcivity.Main;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.restatr.Atcivity.KitchenHelper.Bean.DishesBean;
import com.example.restatr.Atcivity.KitchenHelper.DetailsOfDishesAt;
import com.example.restatr.Atcivity.LawyerConsultation.Bean.LawyerInfoBean;
import com.example.restatr.Atcivity.LawyerConsultation.LawyerInfoAt;
import com.example.restatr.Atcivity.PetHospital.Bean.PawsClawsPetVetBean;
import com.example.restatr.Atcivity.PetHospital.PetDoctorDetailsAt;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SearchAt extends AppCompatActivity {
    private EditText search;
    private RecyclerView rv;
    private TextView cancel;
    private List<DishesBean.RowsBean> dishesRows = new ArrayList<>();
    private List<PawsClawsPetVetBean.RowsBean> petHospitalRows = new ArrayList<>();
    private List<LawyerInfoBean.RowsBean> lawyerInfoRows = new ArrayList<>();
    private KitchenHelperAdapter KitchenHelperAdapter = new KitchenHelperAdapter();
    private LinearLayout Null;
    private TextView nullText;
    private LinearLayout loading;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_search_at );
        search = findViewById( R.id.search );
        rv = findViewById( R.id.rv );
        cancel = findViewById( R.id.cancel );
        Null = findViewById( R.id.Null );
        nullText = findViewById( R.id.null_text );
        loading = findViewById( R.id.loading );
        nullText.setText( "暂无内容..." );
        search.addTextChangedListener( new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                switch (getIntent().getStringExtra( "intent" )) {
                    case "宠物医院":
                        GetDoctorList();
                        break;
                    case "厨房助手":
                        GetAllDishes();
                        break;
                    case "法律咨询":
                        GetLawyerInfo();
                        break;
                }
                if (!search.getText().toString().trim().isEmpty()) {
                    search.setCompoundDrawablesWithIntrinsicBounds( getDrawable( R.drawable.ic_baseline_search_24 ), null, getDrawable( R.drawable.ic_round_cancel_24 ), null );
                } else {
                    search.setCompoundDrawablesWithIntrinsicBounds( getDrawable( R.drawable.ic_baseline_search_24 ), null, null, null );
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        } );
        //搜索框清除按钮点击事件
        search.setOnTouchListener( new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Drawable drawable = search.getCompoundDrawables()[2];
                if (drawable == null)
                    return false;
                if (event.getX() > search.getWidth()
                        - search.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {
                    search.setText( "" );
                }
                return true;
            }
        } );
        cancel.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        } );

    }

    @Override
    protected void onResume() {
        super.onResume();
        switch (getIntent().getStringExtra( "intent" )) {
            case "宠物医院":
                GetDoctorList();
                break;
            case "厨房助手":
                GetAllDishes();
                break;
            case "法律咨询":
                GetLawyerInfo();
                break;
        }
    }

    /**
     * 宠物医院
     * 获取所有医生
     */
    private void GetDoctorList() {
        petHospitalRows.clear();
        loading.setVisibility( View.VISIBLE );
        new Thread( () -> {
            String token = Tools.Get( "/prod-api/api/pet-hospital/pet-doctor/list?name=" + search.getText().toString(), MainActivity.sp.getString( "token", "" ) );
            PawsClawsPetVetBean rowsBean = new Gson().fromJson( token, PawsClawsPetVetBean.class );
            petHospitalRows.addAll( rowsBean.getRows() );
            runOnUiThread( () -> {
                loading.setVisibility( View.GONE );
                if (petHospitalRows.size() > 0) {
                    rv.setAdapter( new PetHospitalAdapter() );
                    rv.setVisibility( View.VISIBLE );
                    Null.setVisibility( View.GONE );
                } else {
                    rv.setVisibility( View.GONE );
                    Null.setVisibility( View.VISIBLE );
                }
            } );
        } ).start();
    }

    /**
     * 厨房助手
     * 获取所有菜品
     */
    private void GetAllDishes() {
        dishesRows.clear();
        loading.setVisibility( View.VISIBLE );
        new Thread( () -> {
            String token = Tools.Get( "/prod-api/api/kitchen-helper/dishes/list?name=" + search.getText().toString(), MainActivity.sp.getString( "token", "" ) );
            DishesBean dishesBean = new Gson().fromJson( token, DishesBean.class );
            dishesRows.addAll( dishesBean.getRows() );
            runOnUiThread( () -> {
                loading.setVisibility( View.GONE );
                if (dishesRows.size() > 0) {
                    rv.setAdapter( KitchenHelperAdapter );
                    rv.setVisibility( View.VISIBLE );
                    Null.setVisibility( View.GONE );
                } else {
                    rv.setVisibility( View.GONE );
                    Null.setVisibility( View.VISIBLE );
                }
            } );
        } ).start();
    }

    /**
     * 法律咨询
     * 获取律师信息
     */
    private void GetLawyerInfo() {
        lawyerInfoRows.clear();
        loading.setVisibility( View.VISIBLE );
        new Thread( () -> {
            String token = Tools.Get( "/prod-api/api/lawyer-consultation/lawyer/list?name=" + search.getText().toString(), MainActivity.sp.getString( "token", "" ) );
            LawyerInfoBean lawyerInfoBean = new Gson().fromJson( token, LawyerInfoBean.class );
            lawyerInfoRows.addAll( lawyerInfoBean.getRows() );
            runOnUiThread( () -> {
                loading.setVisibility( View.GONE );
                if (lawyerInfoRows.size() > 0) {
                    rv.setAdapter( new LawyerInfoAdapter() );
                    rv.setVisibility( View.VISIBLE );
                    Null.setVisibility( View.GONE );
                } else {
                    rv.setVisibility( View.GONE );
                    Null.setVisibility( View.VISIBLE );
                }
            } );
        } ).start();
    }

    /**
     * 厨房助手适配器
     */
    class KitchenHelperAdapter extends RecyclerView.Adapter<KitchenHelperAdapter.viewHolder> {
        @NonNull
        @Override
        public KitchenHelperAdapter.viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = getLayoutInflater().inflate( R.layout.list_item_layout, parent, false );
            return new KitchenHelperAdapter.viewHolder( inflate );
        }

        @Override
        public void onBindViewHolder(@NonNull KitchenHelperAdapter.viewHolder holder, int position) {
            Glide.with( SearchAt.this )
                    .load( Tools.ip + dishesRows.get( position ).getImgUrl() )
                    .transform( new RoundedCorners( 15 ) )
                    .into( holder.tp );
            holder.title1.setText( dishesRows.get( position ).getName() );
            holder.title2.setText( dishesRows.get( position ).getIngredients() );
            holder.text3.setText( String.valueOf( dishesRows.get( position ).getLikeCount() ) );
            holder.text4.setText( String.valueOf( dishesRows.get( position ).getCollectionCount() ) );
            if (dishesRows.get( position ).isMyLikeState()) {
                holder.icon3.setImageResource( R.drawable.ic_baseline_favorite_24 );
            } else {
                holder.icon3.setImageResource( R.drawable.ic_baseline_favorite_border_24 );
            }
            if (dishesRows.get( position ).isMyCollectionState()) {
                holder.icon4.setImageResource( R.drawable.ic_round_star_24 );
            } else {
                holder.icon4.setImageResource( R.drawable.ic_round_star_border_24 );
            }
            //点赞/取消点赞某个菜品
            holder.ll3.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Thread( () -> {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put( "dishesId", dishesRows.get( position ).getId() );
                            jsonObject.put( "newState", !dishesRows.get( position ).isMyLikeState() );
                            String token = Tools.Post( "/prod-api/api/kitchen-helper/dishes-like",
                                    MainActivity.sp.getString( "token", "" ), jsonObject.toString() );
                            JSONObject jx = new JSONObject( token );
                            String msg = jx.getString( "msg" );
                            int code = jx.getInt( "code" );
                            runOnUiThread( () -> {
                                Toast.makeText( SearchAt.this, msg, Toast.LENGTH_SHORT ).show();
                                if (code == 200) {
                                    dishesRows.get( position ).setMyLikeState( !dishesRows.get( position ).isMyLikeState() );
                                    if (dishesRows.get( position ).isMyLikeState()) {
                                        dishesRows.get( position ).setLikeCount( dishesRows.get( position ).getLikeCount() + 1 );
                                    } else {
                                        dishesRows.get( position ).setLikeCount( dishesRows.get( position ).getLikeCount() - 1 );
                                    }
                                    KitchenHelperAdapter.notifyItemChanged( position );
                                }
                            } );
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } ).start();

                }
            } );
            //收藏/取消收藏某个菜品
            holder.ll4.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Thread( () -> {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put( "dishesId", dishesRows.get( position ).getId() );
                            jsonObject.put( "newState", !dishesRows.get( position ).isMyCollectionState() );
                            String token = Tools.Post( "/prod-api/api/kitchen-helper/dishes-collection",
                                    MainActivity.sp.getString( "token", "" ), jsonObject.toString() );
                            JSONObject jx = new JSONObject( token );
                            String msg = jx.getString( "msg" );
                            int code = jx.getInt( "code" );
                            runOnUiThread( () -> {
                                Toast.makeText( SearchAt.this, msg, Toast.LENGTH_SHORT ).show();
                                if (code == 200) {
                                    dishesRows.get( position ).setMyCollectionState( !dishesRows.get( position ).isMyCollectionState() );
                                    if (dishesRows.get( position ).isMyCollectionState()) {
                                        dishesRows.get( position ).setCollectionCount( dishesRows.get( position ).getCollectionCount() + 1 );
                                    } else {
                                        dishesRows.get( position ).setCollectionCount( dishesRows.get( position ).getCollectionCount() - 1 );
                                    }
                                    KitchenHelperAdapter.notifyItemChanged( position );
                                }
                            } );
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } ).start();
                }
            } );
            holder.itemView.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent( SearchAt.this, DetailsOfDishesAt.class );
                    intent.putExtra( "id", dishesRows.get( position ).getId() );
                    startActivity( intent );
                }
            } );
        }

        @Override
        public int getItemCount() {
            return dishesRows.size();
        }

        class viewHolder extends RecyclerView.ViewHolder {
            private ImageView tp;
            private TextView title1;
            private TextView title2;
            private LinearLayout ll3;
            private ImageView icon3;
            private TextView text3;
            private LinearLayout ll4;
            private ImageView icon4;
            private TextView text4;

            public viewHolder(@NonNull View itemView) {
                super( itemView );
                tp = itemView.findViewById( R.id.tp );
                title1 = itemView.findViewById( R.id.title1 );
                title2 = itemView.findViewById( R.id.title2 );
                ll3 = itemView.findViewById( R.id.ll3 );
                icon3 = itemView.findViewById( R.id.icon3 );
                text3 = itemView.findViewById( R.id.text3 );
                ll4 = itemView.findViewById( R.id.ll4 );
                icon4 = itemView.findViewById( R.id.icon4 );
                text4 = itemView.findViewById( R.id.text4 );
            }
        }
    }

    /**
     * 宠物医院适配器
     */
    class PetHospitalAdapter extends RecyclerView.Adapter<PetHospitalAdapter.viewHolder> {

        @NonNull
        @Override
        public PetHospitalAdapter.viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = getLayoutInflater().inflate( R.layout.lawyer_item, parent, false );
            return new PetHospitalAdapter.viewHolder( inflate );
        }

        @Override
        public void onBindViewHolder(@NonNull PetHospitalAdapter.viewHolder holder, int position) {
            Glide.with( SearchAt.this )
                    .load( Tools.ip + petHospitalRows.get( position ).getAvatar() )
                    .transform( new CircleCrop() )
                    .into( holder.head );
            holder.name.setText( petHospitalRows.get( position ).getName() );
            holder.workStartAt.setText( "职业证号" + petHospitalRows.get( position ).getPracticeNo() );
            holder.serviceTimes.setText( "从业时间 " + petHospitalRows.get( position ).getWorkingYears() + "年" );
            holder.separate.setVisibility( View.GONE );
            holder.favorableRate.setVisibility( View.GONE );
            holder.legalExpertiseName.setText( petHospitalRows.get( position ).getJobName() );
            holder.itemView.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent( SearchAt.this, PetDoctorDetailsAt.class );
                    intent.putExtra( "data", new Gson().toJson( petHospitalRows.get( position ) ) );
                    startActivity( intent );
                }
            } );
        }

        @Override
        public int getItemCount() {
            return petHospitalRows.size();
        }

        class viewHolder extends RecyclerView.ViewHolder {
            private ImageView head;
            private TextView name;
            private TextView workStartAt;
            private TextView serviceTimes;
            private TextView favorableRate;
            private TextView legalExpertiseName;
            private CardView cardBtn;
            private View separate;


            public viewHolder(@NonNull View itemView) {
                super( itemView );
                head = itemView.findViewById( R.id.head );
                name = itemView.findViewById( R.id.name );
                workStartAt = itemView.findViewById( R.id.workStartAt );
                serviceTimes = itemView.findViewById( R.id.serviceTimes );
                favorableRate = itemView.findViewById( R.id.favorableRate );
                legalExpertiseName = itemView.findViewById( R.id.legalExpertiseName );
                cardBtn = itemView.findViewById( R.id.cardBtn );
                separate = itemView.findViewById( R.id.separate );
            }
        }
    }

    /**
     * 法律咨询适配器
     */
    class LawyerInfoAdapter extends RecyclerView.Adapter<LawyerInfoAdapter.viewHolder> {

        @NonNull
        @Override
        public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = getLayoutInflater().inflate( R.layout.lawyer_item, parent, false );
            return new viewHolder( inflate );
        }

        @Override
        public void onBindViewHolder(@NonNull viewHolder holder, int position) {
            Glide.with( SearchAt.this )
                    .load( Tools.ip + lawyerInfoRows.get( position ).getAvatarUrl() )
                    .transform( new CircleCrop() )
                    .into( holder.head );
            holder.name.setText( lawyerInfoRows.get( position ).getName() );
            holder.workStartAt.setText( "从业时间" + lawyerInfoRows.get( position ).getWorkStartAt() );
            holder.serviceTimes.setText( lawyerInfoRows.get( position ).getServiceTimes() + "人咨询" );
            holder.favorableRate.setText( "好评率" + lawyerInfoRows.get( position ).getFavorableRate() + "%" );
            holder.legalExpertiseName.setText( lawyerInfoRows.get( position ).getLegalExpertiseName() );
            holder.cardBtn.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent( SearchAt.this, LawyerInfoAt.class );
                    intent.putExtra( "data", new Gson().toJson( lawyerInfoRows.get( position ) ) );
                    startActivity( intent );
                }
            } );
        }

        @Override
        public int getItemCount() {
            return lawyerInfoRows.size();
        }

        class viewHolder extends RecyclerView.ViewHolder {
            private ImageView head;
            private TextView name;
            private TextView workStartAt;
            private TextView serviceTimes;
            private View separate;
            private TextView favorableRate;
            private TextView legalExpertiseName;
            private CardView cardBtn;

            public viewHolder(@NonNull View itemView) {
                super( itemView );
                head = itemView.findViewById( R.id.head );
                name = itemView.findViewById( R.id.name );
                workStartAt = itemView.findViewById( R.id.workStartAt );
                serviceTimes = itemView.findViewById( R.id.serviceTimes );
                separate = itemView.findViewById( R.id.separate );
                favorableRate = itemView.findViewById( R.id.favorableRate );
                legalExpertiseName = itemView.findViewById( R.id.legalExpertiseName );
                cardBtn = itemView.findViewById( R.id.cardBtn );
            }
        }
    }


}